import sys
import socket
import threading


def server_loop(local_host, local_port, remote_host, remote_port, receive_first):

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))
        print("bind is finished.")
    except:
        print("[!!] Failed to listen on %s:%d" % (local_host, local_port))
        print("[!!] Check for other listening sockets or correct permissions.")
        sys.exit(0)

    server.listen(5)
    print("server is listened.")
    print(local_host, local_port)

    while True:
        client_socket, addr = server.accept()

        print("[==>] Received incoming connetion from %s:%d" % (addr[0], addr[1]))

        proxy_thread = threading.Thread(target=proxy_handler, args=(client_socket, remote_host, remote_port, receive_first))

        proxy_thread.start()


def main():
    if len(sys.argv[1:]) != 5:
        print("Usage: proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]")
        print("Example: proxy.py 127.0.0.1 9000 10.12.132.1 9000 True")
        sys.exit(0)

    print(sys.argv)

    local_host, local_port, remote_host, remote_port, receive_first = sys.argv[1:]

    receive_first = True if receive_first.lower() is "true" else False

    server_loop(local_host, int(local_port), remote_host, int(remote_port), receive_first)


def proxy_handler(client_socket, remote_host, remote_port, receive_first):
    print("prxy_handler is running.")

    remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    remote_socket.connect((remote_host, remote_port))

    if receive_first:

        remote_buffer = receive_from(remote_socket)
        # hexdump(remote_buffer)

        remote_buffer = response_handler(remote_buffer)

        if len(remote_buffer):
            print("[<==] Sending %d bytes to localhost." % len(remote_buffer))
            client_socket.send(remote_buffer)

    # print("2")
    while True:
        local_buffer = receive_from(client_socket)
        print(local_buffer)

        if len(local_buffer):
            print("[==>] Received %d bytes from localhost." % len(local_buffer))
            # hexdump(local_buffer)

            local_buffer = request_handler(local_buffer)

            remote_socket.send(local_buffer)
            print("[==>] Sent to remote")

        remote_buffer = receive_from(remote_socket)

        if len(remote_buffer):
            print("[<==] Received %d bytes from remote." % len(remote_buffer))
            # hexdump(remote_buffer)

            remote_buffer = response_handler(remote_buffer)

            client_socket.send(remote_buffer)

            print("[<==] Sent to localhost.")
            pass

        if not len(local_buffer) or not len(remote_buffer):
            client_socket.close()
            remote_socket.close()
            print("[*] No more data. Closing connetions.")
            break


def hexdump(src, length=16):
    result = []
    digits = 4 if isinstance(src, str) else 2

    for i in range(0, len(src), length):
        s = src[i: i+length]
        hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
        text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
        result.append(b"%04X  %-*s" % (i, length*(digits + 1), hexa, text))

    print(b'\n'.join(result))
    pass


def receive_from(connetion):
    buffer = b""
    connetion.settimeout(5)

    try:
        while True:
            data = connetion.recv(4096)
            # print("data is" + str(data))

            if not data:
                break

            buffer += data

    except:
        pass

    return buffer
    pass


def response_handler(buffer):
    return buffer
    pass


def request_handler(buffer):
    return buffer
    pass


if __name__ == '__main__':
    # local_host = remote_host = '0.0.0.0'
    # local_port = remote_port = 9999
    # receive_first = ""
    # server_loop(local_host, local_port, remote_host, remote_port, receive_first)

    main()